package com.eascs.admin.o2o.backFees.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.backFees.entity.O2oBackFeesEntity;
import com.eascs.admin.o2o.backFees.service.O2oBackFeesService;
import com.eascs.admin.o2o.backFees.vo.O2oBackFeesVo;
import com.eascs.admin.o2o.backfee.entity.FormBackFeeEntity;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.notice.controller.NoticeBaseMasterController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.context.RequestContext;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("/backfees")
public class O2oBackFeesController extends NoticeBaseMasterController {

	private static Logger logger = LoggerFactory.getLogger(O2oBackFeesController.class);

	@Reference
	SysOrgService sysOrgService;

	@Reference
	CustomerService customerService;

	@Autowired
	O2oBackFeesService o2oBackFeesService;

	/**
	 * @Title: index
	 * @Description: 新增征信-查询客户
	 * @author yy
	 * @return
	 * @return String
	 * @throws @date 2017年11月30日 下午20:17:31
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(String idCard, String name) {
		// try {
		// name=new String(name.getBytes("ISO-8859-1"),"GB2312");
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "backFeesAddNew1");
		if (StringUtil.isNotBlank(idCard)) {
			idCard = idCard.trim();
		}
		ViewContext.put("idCard", idCard);
		ViewContext.put("name", name);
		logger.info("idCard:", idCard + "-------" + name);
		return "backfees/index";

	}

	/**
	 * @Title: search
	 * @Description: 根据查询结果跳转到申请借款-编辑客户信息 或者申请借款-增加客户信息
	 * @author yy
	 * @param idCard
	 * @return
	 * @return String
	 * @throws @date 2017年11月30日 下午20:17:44
	 */
	@RequestMapping(value = "/search")
	public String search(String idCard, String name, String id) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "nzx_search");
		if (StringUtil.isNotBlank(idCard)) {
			idCard = idCard.trim();
		}
		O2oBackFeesEntity o2oBackFees = null;
		if (StringUtil.isNotBlank(id)) {
			o2oBackFees = o2oBackFeesService.queryById(id);
		}
		if (o2oBackFees != null) {
			ViewContext.put("entity", o2oBackFees);
			ViewContext.put("idCard", o2oBackFees.getDocumentNo());
		} else {
			ViewContext.put("entity", new O2oBackFeesEntity());
			ViewContext.put("idCard", idCard);
		}
		CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);

		ViewContext.put("name", name);
		ViewContext.put("vo", basic);
		return "/backfees/editBackFees";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String search(O2oBackFeesVo vo) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "grtk_liebiao");
		vo.setPageSize(BaseUtils.PAGE_SIZE);
		String export = "/backfees/export";
		String name = vo.getName() == null ? "" : vo.getName();
		String idCard = vo.getIdCard() == null ? "" : vo.getIdCard();
		String createStartTime = vo.getCreateStartTime() == null ? "" : vo.getCreateStartTime();
		String createEndTime = vo.getCreateEndTime() == null ? "" : vo.getCreateEndTime();
		String status = vo.getStatus() == null ? "" : vo.getStatus();
		String createName = vo.getCreateName() == null ? "" : vo.getCreateName();
		String ltdName = vo.getLtdName() == null ? "" : vo.getLtdName();
		boolean queryAll = vo.isQueryAll();
		export = UrlUtil.appendUrl(export, "name", name);
		export = UrlUtil.appendUrl(export, "idCard", idCard);
		export = UrlUtil.appendUrl(export, "createStartTime", createStartTime);
		export = UrlUtil.appendUrl(export, "createEndTime", createEndTime);
		export = UrlUtil.appendUrl(export, "status", status);
		export = UrlUtil.appendUrl(export, "createName", createName);
		export = UrlUtil.appendUrl(export, "ltdName", ltdName);
		if(queryAll){
			export = UrlUtil.appendUrl(export, "queryAll", queryAll + "");
		}
		/*
		 * List<User>
		 * users=sysOrgService.checkDataPermission(UserHolder.getUser(
		 * ).getNo()); String no=""; if (users!=null) { for (User user : users)
		 * { no+=user.getNo()+","; } } if (!"".equals(no)) { if
		 * (",".equals(no.substring(no.length()-1, no.length()))) {
		 * no=no.substring(0, no.length()-1); } } logger.info("userno={}", no);
		 * vo.setType(no);
		 */
		PageResult<Object[]> pageResult = o2oBackFeesService.findByPage(vo);
		String[] titles = { "单号", "创建人", "经办平台", "姓名", "证件号码", "退款金额（元）", "创建时间", "单据状态" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, new SelectDataOption("O2O_BILLSTATUS") };
		String pageUrl = UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageIndex", "");
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		Button[] titleButton = new Button[] { ButtonHelper.createRedirectButton(null, "/backfees/list_detail?id=") };
		paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", vo);
		ViewContext.put("export", export);
		return "/backfees/list";
	}
	
	@RequestMapping("/export")
	public void export(O2oBackFeesVo vo, HttpServletResponse httpServletResponse){
		try {
			httpServletResponse.setHeader("Content-Disposition", "attachment;filename=backfees.xls");
			httpServletResponse.setContentType("appliction/octet-stream;charset=utf-8");
			String sourceFileName = "/excelTemplate/backfees.xls";
			vo.setPageSize(Integer.MAX_VALUE);
			PageResult<Object[]> pageResult = o2oBackFeesService.findByPageExport(vo);
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oBackFeesController.class.getResourceAsStream(sourceFileName), defaultRowWriteHandler);
		} catch (IOException e) {
			logger.error("退款导出错误，信息：【{}】", e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 列表详情页
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/list_detail")
	public String detail(String id, String massege) {
		// User user = UserHolder.getUser();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "detail_grdk_liebiao");
		O2oBackFeesEntity o2oBackFees = o2oBackFeesService.queryById(id);

		Button button = ButtonHelper.createAjaxButton("启动流程", "/work/newTXstartup?loanapplyNo=" + o2oBackFees.getId());
		button.setPermissionCode("o2oBackFeesStartFlowButton");
		// *****loan-12273 征信查询单据删除功能 start
		AjaxConfirmButton delBtn = new AjaxConfirmButton("删除", "/rbackfees/delete?id=" + o2oBackFees.getId());
		delBtn.setPermissionCode("o2oBackFeesDelete");
		delBtn.setConfirmMessage("删除数据不可恢复，确认删除？");
		List<Button> btnS = new ArrayList<Button>();
		btnS.add(button);
		btnS.add(delBtn);
		// **********end
		ViewContext.put("buttons", btnS);
		String approvUrl = "/wf/processNode/agreeInfo?referId=" + o2oBackFees.getId() + "&amp;processType=ACCOUNT_REFUND";
		ViewContext.put("errorMassege", massege);
		ViewContext.put("approvUrl", approvUrl);
		ViewContext.put("o2oBackFees", o2oBackFees);
		/*
		 * String datalistReadonly = "true"; ViewContext.put("datalistReadonly",
		 * datalistReadonly);
		 */

		StringBuffer o2oPageUrl = new StringBuffer("/rbackfee/o2obackfee");
		String o2oUrl = "";

		CustomerEntity loaner = customerService.queryCustomerEntityByIdCard(o2oBackFees.getDocumentNo());
		CustomerEntity spouse = loaner.getSpouse();

		if (spouse != null) {

			logger.info("配偶信息:", spouse.getIdNumber() + "-------" + spouse.getCustomerName());

		}

		FormBackFeeEntity formBackFee = new FormBackFeeEntity();
		if (formBackFee != null) {
			String customerId = loaner.getCustomerId() == null ? "" : loaner.getCustomerId();
			String spouseId = "";
			if (spouse != null) {
				spouseId = spouse.getCustomerId() == null ? "" : spouse.getCustomerId();
			}
			o2oUrl = UrlUtil.appendUrl(o2oPageUrl.toString(), "customerId", customerId);
			o2oUrl = UrlUtil.appendUrl(o2oUrl.toString(), "spouseId", spouseId);

		}
		o2oUrl = o2oUrl + "&showO2oPage=";

		ViewContext.put("o2oBackfeeUrl", o2oUrl);

		if (loaner != null) {
			ViewContext.put("customerIdCard", loaner.getIdNumber());
			ViewContext.put("accountId", loaner.getAccountId());
		} else {
			ViewContext.put("customerIdCard", null);
			ViewContext.put("accountId", null);
		}

		if (spouse != null) {
			ViewContext.put("spouseIdCard", spouse.getIdNumber());
		} else {
			ViewContext.put("spouseIdCard", null);
		}

		return "backfees/list_detail";
	}

}
